package com.sniff.atp.service.purchase;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ckbs.purchase.enums.PurchaseOrderStatusEnum;
import com.sniff.atp.constant.LoginConstant;
import com.sniff.atp.dto.SystemLoginDTO;
import com.sniff.atp.enums.api.PurchaseAPI;
import com.sniff.atp.service.order.PurchaseAllotOrder;
import com.sniff.atp.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.service.purchase
 * @Author: zxy
 * @CreateTime: 2022-10-28 16:41
 * @Description: 采购模块
 * @Version: 1.0
 */
@Service
public class PurchaseService {
    private SystemLoginDTO systemLoginDTO;

    @Autowired
    private DKPurchaseService dkPurchaseService;
    @Autowired
    private PurchaseAllotOrder purchaseAllotOrder;
    @Autowired
    private OEMPurchaseService oemPurchaseService;
    @Autowired
    private PurchaseService purchaseService;


    /**
     * 指定订单分单
     *
     * @param systemLoginDTO
     * @param platformOrderNos
     * @return
     */
    public String allotAutoOrder(SystemLoginDTO systemLoginDTO, String... platformOrderNos) {

        JSONArray jsonArray = new JSONArray();

        Arrays.stream(platformOrderNos).forEach((item)->{
            jsonArray.add(item);
        });

        JSONObject param = new JSONObject();
        param.put("platformOrderNos", jsonArray);
        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.ALLOTE_ORDER.getApi(), param);
    }

    /**
     * 平台端：设置登录token
     *
     * @param systemLoginDTO
     */
    public void setPurchaseToken(SystemLoginDTO systemLoginDTO) {
        this.systemLoginDTO = systemLoginDTO;
    }

    public String changePurchaseUser(String purchaseId, int modifyType) {
        JSONObject param = JsonUtil.readJson("purchase/changePurchaseUser");
        param.replace("modifyType", modifyType);
        param.getJSONArray("changeUsers").getJSONObject(0).replace("purchaseId", purchaseId);
        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.CHANGE_PURCHASE_USER.getApi(), param);
    }
    public String submitOrder(String purchaseId) {
        JSONObject param = new JSONObject();
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(purchaseId);
        param.put("purchaseIds", arrayList);
        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.SUBMIT_ORDER.getApi(), param);
    }

    /**
     * 平台端：采购单列表查询
     */
    public String listPurchase(String purchaseNo) {
        JSONObject param = JsonUtil.readJson("purchase/listPurchase");
        ArrayList<String> paramList = new ArrayList<>();
        paramList.add(purchaseNo);
        param.replace("purchaseNos", paramList);
        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.PURCHASE_LIST.getApi(), param);
    }

    public String handeCreateOrder(String purchaseId) {
        JSONObject param = JsonUtil.readJson("purchase/handeCreateOrder");
        param.replace("purchaseId", purchaseId);
        param.replace("payTime", DateUtil.dateToDay(new Date()));
        param.replace("tbOrderNo", "QDDH"+DateUtil.longString());
        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.HANDE_CREATE_ORDER.getApi(), param);
    }

    public String pushStallApplet(String purchaseId){
        JSONObject param = new JSONObject();
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(purchaseId);
        param.put("purchaseIds", arrayList);
        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.PUSH_STALL_APPLET.getApi(), param);
    }

    public String editLogistcNumbers(String purchaseId) {
        JSONObject param = JsonUtil.readJson("purchase/editLogistcNumbers");
        param.replace("purchaseId", purchaseId);
        JSONObject expressNo = param.getJSONArray("expressNo").getJSONObject(0);
        String expressNumber = "SF"+DateUtil.longString();
        expressNo.replace("logisticsNumber",expressNumber);
        expressNo.replace("purchaseEstimateStockTime", DateUtil.dateToDay(new Date()));

        ToolsUtil.stringBuild("logisticsNumber", expressNumber);
        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.EDIT_LOGISTC_NUMBER.getApi(), param);
    }

    /**
     * 平台端：采购单详情
     */
    public String purchaseInfo(String puchaseId) {
        JSONObject param = new JSONObject();
        param.put("purchaseId", puchaseId);

        String result = new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.PURCHASE_INFO.getApi(), param);
        return result;
    }

    /**
     * 平台端：编辑采购单信息
     *
     * @Description:
     * @param: systemSourceName D2C, B2B
     * @param: orderTotalMoney 采购单总金额
     * @param: purchaseId
     * @Return: java.lang.String
     * @Author: zxy
     * @Date: 2022/10/31 21:00
     * @Version: 1.0
     */
    public String editOnlinePurchaseOrder(String systemSourceName, Integer orderTotalMoney, String purchaseId) {
        JSONObject param = JsonUtil.readJson("purchase/editOnlinePurchaseOrder");
        String tbOrderNo = "CGD" + RandomUtil.numberString(10);
        param.replace("tbOrderNo", tbOrderNo);
        param.replace("orderTotalMoney", orderTotalMoney);

        String expressNo = "SFP" + RandomUtil.numberString(10);
        param.getJSONArray("expressNoList").getJSONObject(0).replace("logisticsNumber", expressNo);

        param.replace("purchaseId", purchaseId);
        param.replace("purchaseMoney", (orderTotalMoney - 10));
        param.replace("payTime", DateUtil.dateToString(new Date()));

        if (!systemSourceName.equals("D2C")) {
            String[] accountList = {"B2B", "支付宝", "test"};
            param.replace("accountList", accountList);
        }

        ToolsUtil.stringBuild("logisticsNumber", expressNo);

        String result = new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.editOnline_Purchase_Order.getApi(), param);
        return result;
    }

    /**
     * 平台端：编辑采购单商品信息
     */
    public String editPurchaseItem(String purchaseNum, String purchaseItemId) {
        JSONObject param = JsonUtil.readJson("purchase/editOnlinePurchaseOrderItem");
        param.replace("purchaseNum", purchaseNum);
        param.replace("purchaseItemId", purchaseItemId);

        return new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.editOnline_Purchase_Item.getApi(), param);
    }

    /**
     * 平台端：档口采购单按商品编辑
     */
    public String editStallPurchaseItem(String purchaseItemId) {
        JSONObject param = JsonUtil.readJson("purchase/editStallPurchaseItem");
        param.replace("purchaseItemId", purchaseItemId);
        String result = new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.editStall_Purchase_Item.getApi(), param);
        return result;
    }

    /**
     * 平台端：采购完成提交
     */
    public String completeOnlinePurchaseOrder(String purchaseId) {
        JSONObject param = new JSONObject();
        param.put("id", purchaseId);

        ToolsUtil.sleep(1000 * 3);
        String result = new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.complete_Online_Purchase_Order.getApi(), param);
        return result;
    }

    /**
     * 平台端：查询档口市场获取markCode
     */
    public String mallList(String mallName) {
        JSONObject param = new JSONObject();
        param.put("parentId", "");
        param.put("status", 1);

        String result = new HttpClientUtil(Headers.setSystemHeader(systemLoginDTO)).doPostJson(PurchaseAPI.PURCHASE_MALL_LIST.getApi(), param);
        JSONObject object = JSON.parseObject(result);
        JSONArray data = object.getJSONArray("data");
        for (Object mallData : data) {
            String title = ((JSONObject) mallData).getString("title");
            String marketCode = ((JSONObject) mallData).getString("marketCode");
            if (mallName.equals(title)) {
                return marketCode;
            }
        }

        return mallName;
    }

    /**
     * 档口采购流程
     */
    public void dkMarketPrcess(String stallName, String purchaseNo) {
        String marketCode = mallList(stallName);
        LogUtil.warn("【档口采购】查询档口市场，获取marketCode: " + marketCode);

        dkPurchaseService.dklogin(stallName);
        String pagetask = dkPurchaseService.pageTakeOrder(marketCode, purchaseNo, "0");
        LogUtil.warn("【档口采购】登录小程序，查询拿货单；拿货市场：" + stallName);

        String takeOrderId = JsonUtil.extractString(pagetask, "data.records[0].takeOrderId");
        dkPurchaseService.takeOrders(takeOrderId);
        LogUtil.warn("【档口采购】小程序接单，拿货单takeOrderId： " + takeOrderId);

        String pagetask1 = dkPurchaseService.pageTakeOrder(marketCode, purchaseNo, "1");
        LogUtil.warn("【档口采购】查询已接单记录！！");

        JSONObject object = JSON.parseObject(pagetask1);
        JSONArray jsonArray = object.getJSONObject("data").getJSONArray("records");
        for (Object o : jsonArray) {
            String takeOrderId1 = ((JSONObject) o).getString("takeOrderId");
            Integer num = ((JSONObject) o).getInteger("num");
            dkPurchaseService.saveTakeRecord(takeOrderId1, num);
        }
        LogUtil.warn("【档口采购】添加拿货记录，并提交！！");
    }

    public String purchaseStatusNext(String purchaseNo) {


        String listPurchase = listPurchase(purchaseNo);
        LogUtil.warn("【线上采购】查询采购单，单号：" + purchaseNo);

        String purchaseId = JsonUtil.extractString(listPurchase, "data.records[0].purchaseId");
        String purchaseOrderStatus = JsonUtil.extractString(listPurchase, "data.records[0].purchaseOrderStatus");

        if (purchaseOrderStatus.equals(PurchaseOrderStatusEnum.WAIT_DISTRIBUTE.getType().toString())) {
            changePurchaseUser(purchaseId, 1);
            changePurchaseUser(purchaseId, 2);
        }

        if (purchaseOrderStatus.equals(PurchaseOrderStatusEnum.WAIT_CHANGE_URL.getType().toString())) {
            submitOrder(purchaseId);
        }

        if (purchaseOrderStatus.equals(PurchaseOrderStatusEnum.WAIT_CREATE_ORDER.getType().toString())) {
            handeCreateOrder(purchaseId);
        }
        if (purchaseOrderStatus.equals(PurchaseOrderStatusEnum.WAIT_PAY.getType().toString())) {
            if (purchaseNo.contains("DKCGD")){
                pushStallApplet(purchaseId);
            }
        }
        if (purchaseOrderStatus.equals(PurchaseOrderStatusEnum.WAIT_SUPPLIER_DELIVERY.getType().toString())) {
            if (purchaseNo.contains("DKCGD")) {
                String stallName = JsonUtil.extractString(listPurchase, "data.records[0].stallName");
                dkMarketPrcess(stallName, purchaseNo);
            }else{
                editLogistcNumbers(purchaseId);
            }
        }
        if (purchaseOrderStatus.equals(PurchaseOrderStatusEnum.WAIT_RECEIVER.getType().toString())) {
        }
        if (purchaseOrderStatus.equals(PurchaseOrderStatusEnum.COMPLETE.getType().toString())) {
        }
        if (purchaseOrderStatus.equals(PurchaseOrderStatusEnum.CANCEL.getType().toString())) {
        }

        listPurchase = listPurchase(purchaseNo);
        purchaseOrderStatus = JsonUtil.extractString(listPurchase, "data.records[0].purchaseOrderStatus");
        LogUtil.info("【采购】采购单状态：" + PurchaseOrderStatusEnum.getMessageByType(Integer.valueOf(purchaseOrderStatus)));
        return purchaseOrderStatus;
    }

    /**
     * 平台端：线上采购流程
     */
    public void puchasePrecess(SystemLoginDTO systemLoginDTO, String purchaseNo) {
        setPurchaseToken(systemLoginDTO);
        String purchaseOrderStatus = "0";
        int num = 0;
        while(!purchaseOrderStatus.equals(PurchaseOrderStatusEnum.WAIT_RECEIVER.getType().toString()) && num < 10){
            purchaseOrderStatus = purchaseStatusNext(purchaseNo);
            num++;
        }
    }


    /**
     * @param systemLoginDTO
     * @param purchaseNo
     * @param node 0.待分配，1 待换源，2 待下单，3 待支付，4 代发货，5 待收货，6 已完成
     */
    public Object purchaseAllProcess(SystemLoginDTO systemLoginDTO, String purchaseNo, Integer node) {
        setPurchaseToken(systemLoginDTO);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("purchaseOrderNo", purchaseNo);

        String listPurchase = listPurchase(purchaseNo);
        String purchaseOrderStatus = JsonUtil.extractString(listPurchase, "data.records[0].purchaseOrderStatus");

        int num = 0;
        while(!purchaseOrderStatus.equals(PurchaseOrderStatusEnum.WAIT_RECEIVER.getType().toString()) && num < 10){
            if(purchaseOrderStatus.equals(String.valueOf(node))){
                return jsonObject;
            }

            purchaseOrderStatus = purchaseStatusNext(purchaseNo);
            num++;

            if(purchaseOrderStatus.equals(String.valueOf(node))){
                return jsonObject;
            }
        }
        return jsonObject;
    }


    /**
     * 根据订单号执行采购流程
     *
     * @param systemLoginDTO
     * @param platformOrderNo
     */
    public void purchaseOrderProcess(SystemLoginDTO systemLoginDTO, String platformOrderNo) {

        String purchaseOrderNo = purchaseAllotOrder.getPurchaseOrderNo(platformOrderNo);

        if (purchaseOrderNo.equals("{}")) {

            purchaseService.allotAutoOrder(LoginConstant.systemLoginDTO, platformOrderNo);
            //暂时使用接口分单，xxljob需要更换成powerjob
            purchaseOrderNo = purchaseAllotOrder.getPurchaseOrderNo(platformOrderNo);
        }

        JSONObject object = JSON.parseObject(purchaseOrderNo);
        JSONArray purchase_nos = object.getJSONArray("purchaseNo");
        for (int i = 0; i < purchase_nos.size(); i++) {
            String purchaseNo = purchase_nos.getString(i);
            if (purchaseNo.contains("DHCGD")) {
                oemPurchaseService.oemPurchaseProcess(systemLoginDTO, purchaseNo);
            }else {
                puchasePrecess(systemLoginDTO, purchaseNo);
            }
        }
    }
}
